﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace FileDuplicateRemover.Gui
{
    public abstract class GridItemSortComparer : IComparer<GridItem>
    {
        private readonly ListSortDirection _sortDirection;

        public GridItemSortComparer(ListSortDirection direction)
        {
            this._sortDirection = direction;
        }

        public int Compare(GridItem x, GridItem y)
        {
            int res = 0;

            if (x == null)
            {
                if (y != null)
                    res = -1;
            }
            else if (y == null)
            {
                res = 1;
            }
            else
            {
                res = CompareCore(x, y);
            }

            if (res != 0 && _sortDirection == ListSortDirection.Descending)
                res = -res;

            return res;
        }

        protected virtual int CompareCore(GridItem x, GridItem y)
        {
            int res;
            res = CompareCore2(x, y);

            if (res == 0)
            {
                res = Comparer<string>.Default.Compare(x.ID, y.ID);

                if (res == 0)
                {
                    res = Comparer<DateTime>.Default.Compare(x.Created, y.Created);
                }
            }
            return res;
        }

        protected abstract int CompareCore2(GridItem x, GridItem y);
    }
}
